﻿using System;
using System.Linq;
using Coolite.Ext.Web;
using Pap.Web.Modules.Administration.ViewModel;
using Pap.Web.Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Administration.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ProjectsList : BasePage<ProjectsListViewModel>, IPermittedPage
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.ViewModel != null)
            {
                projectsStore.DataSource = this.ViewModel.GetAllProjects().ToArray().OrderBy(p => p.Stages.Last().Stage);
                projectsStore.DataBind();
            }
        }

        /// <summary>
        /// Handles the Commad event of the gvProjects control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void gvProjects_Commad(object sender, AjaxEventArgs e)
        {
            RowSelectionModel model = gvProjects.SelectionModel.Primary as RowSelectionModel;
            Guid projectId = e.ExtraParams["ID"].ToString().ToGuid();
            if (e.ExtraParams["CommandName"].Equals("Edit"))
            {
                Ext.Redirect(string.Format("~/Administration.route/ProjectDetails?ProjectId={0}", projectId), GetLocalResourceObject("MSGRedirecting").ToString());
            }
        }

        /// <summary>
        /// Deletes the project.
        /// </summary>
        /// <param name="str">The STR.</param>
        [AjaxMethod]
        public void DeleteProject(string str)
        {
            try
            {
                this.ViewModel.DeleteLastProject();
                //---------------------------------------------------------------
                projectsStore.DataSource = this.ViewModel.GetAllProjects();
                projectsStore.DataBind();
                gvProjects.Reload();
            }
            catch
            {
                Ext.Msg.Alert(GetLocalResourceObject("MBErrorCaption").ToString(), GetLocalResourceObject("MBCouldntDelete").ToString()).Show();
            }
        }

        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "ProjectList"; }
        }

        #endregion
    }
}
